package com.haozi.security.vertify;

import com.haozi.common.Constants;
import com.haozi.security.config.SignConfig;
import com.haozi.security.exception.SignException;
import com.haozi.security.exception.SignExpireException;

import com.haozi.security.exception.SignMismatchingException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.Map;
import java.util.Objects;
import java.util.TreeMap;

/**
 * @author zyh
 * @version 1.0
 * @date 2022/11/5 5:26 下午
 */

public class SignVertify {

    private static final Logger log = LoggerFactory.getLogger(SignVertify.class);


    @Autowired
    SignConfig signConfig;


    public  String sign(String bodyParam, String key,Long currentTimeSeconds,String randomKey) {
        StringBuilder stringBuilder = new StringBuilder();

        String preSign = stringBuilder.append(bodyParam)
                .append("&randomKey=")
                .append(randomKey)
                .append("&key=")
                .append(key).toString();

        String sign = getMD5(preSign).toUpperCase();
        return sign;
    }

    public  void verify(String bodyParam,
                        String key,
                        Long currentTimeSeconds,
                        String randomKey,
                        String sign) {

        long timeStamp = Long.valueOf(currentTimeSeconds);
        long expireTime = timeStamp + signConfig.getExpireTime();
        long currentTimeMillis = System.currentTimeMillis();
        if (System.currentTimeMillis() / 1000 > expireTime) {
            throw new SignExpireException(currentTimeMillis,timeStamp);
        }
        String signServer = sign(bodyParam, key,currentTimeSeconds,randomKey);

        if (!Objects.equals(signServer, sign)) {
            log.info("验签失败,传入sign:{},map:{},currentTumeSeconds{},randomKey",sign,bodyParam,currentTimeSeconds);
            throw new SignMismatchingException();
        }
    }

    /**
     * 生成md5
     *
     * @param
     * @return
     */
    public static String getMD5(String str) {
        String base = str;
        String md5 = DigestUtils.md5DigestAsHex(base.getBytes());
        return md5;
    }
}
